package com.wangp.mywrite.s_netty.netty.ch7;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;

/**
 * @author tooStronger
 * @date 2023/4/16
 */
public class TestLengthFieldDecoder {

    public static void main(String[] args) {
        EmbeddedChannel ec = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(
                        // 最大长度
                        1024,
                        // 长度字节偏移量
                        0,
                        // int 长度4个字节
                        4,
                        // 长度之后调整字节数
                        1,
                        // 长度字节可以跳过
                        4),
                new LoggingHandler(LogLevel.DEBUG)
        );

        // 4 个字节的内容长度，实际内容
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        send(buffer, "Hello, world");
        send(buffer, "Hi!");
        ec.writeInbound(buffer);
    }

    private static void send(ByteBuf buffer, String content) {
        // 实际内容
        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        // 实际内容长度
        int len = bytes.length;
        buffer.writeInt(len);
        // 假设一个字节的版本号
        buffer.writeByte(1);
        buffer.writeBytes(bytes);
    }
}
